//
//  WalletsViewController.m
//  Wallets Manager
//
//  Created by Nguyen Chi Cong on 9/13/12.
//  Copyright (c) 2012 BKHN. All rights reserved.
//

#import "WalletsViewController.h"
#import "DataBaseAccess.h"

#define kRowHeight 50

@implementation WalletsViewController

@synthesize table;
@synthesize walletsList;
@synthesize manageWalletView;
@synthesize delegate;
@synthesize popupView;
@synthesize addWalletView;
@synthesize editButton;
@synthesize deleteButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //=======================Notification Center ===================//
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadTableView :) name:@"reloadTableView" object:nil];
}

- (void)viewDidUnload {
    [self setManageWalletView:nil];
    [self setAddWalletView:nil];
    [self setPopupView:nil];
    [self setEditButton:nil];
    [self setDeleteButton:nil];

  //  [super viewDidUnload];
    table           = nil;
    walletsList     = nil;
    delegate        = nil;
}

-(void)viewWillAppear:(BOOL)animated
{
    walletsList = [[NSMutableArray alloc] initWithArray:[DataBaseAccess getAllWallet]
                   ];  
    [table reloadData];
    [super viewWillAppear:YES];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - TableView Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [walletsList count];
}

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRowHeight;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *WalletIdentifier = @"WalletIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:WalletIdentifier];
    
    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongPress:)];
    Wallet *tempWallet = [walletsList objectAtIndex:indexPath.row];
    
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:WalletIdentifier];
        
        [cell addGestureRecognizer:longTap];
        
    }
    cell.imageView.image = [UIImage imageNamed:tempWallet.w_image];
    if(indexPath.row % 5 == 0)
        cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"lock-open-02.png"]];
    else
        cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"lock-05"]];
    
    cell.textLabel.text = [[walletsList objectAtIndex:indexPath.row] w_name];;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@$", [[walletsList objectAtIndex:indexPath.row] w_balance]];
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   ((folyAppDelegate *)[[UIApplication sharedApplication]delegate]).currentWallet = [walletsList objectAtIndex:indexPath.row];

    [self.navigationController pushViewController:gTabBarController animated:YES];
   // [self.delegate walletDidSelected:[walletsList objectAtIndex:indexPath.row]];
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    Wallet *wallet = [walletsList objectAtIndex:indexPath.row];
    [DataBaseAccess deleteWallet:wallet];
    [walletsList removeObject:wallet];
    
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark - IBAction
-(IBAction)editChange:(id)sender
{
    
}

-(IBAction)addWallet:(id)sender
{
    AddWalletViewController *addWallerViewController = [[AddWalletViewController alloc]init];
    [self.navigationController pushViewController:addWallerViewController animated:YES];
    
}

- (IBAction)editButtonClicked:(id)sender {
    NSLog(@"edit");
}

- (IBAction)deleteButtonClicked:(id)sender {
    NSLog(@"delete");
    NSLog(@"%@",currentWallet);
    [DataBaseAccess deleteWallet:currentWallet];
    NSLog(@"%@", walletsList);
    [walletsList removeObject:currentWallet];
    //[self didDismissModal:popup];
    [popup dismissModal];
    [table deleteRowsAtIndexPaths:[NSArray arrayWithObject:myIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark - UIGesture Delegate

-(void) handleLongPress: (UIGestureRecognizer *)longPress {
    
    CGPoint p = [longPress locationInView:self.table];
    
    NSIndexPath *indexPath = [self.table indexPathForRowAtPoint:p];
    myIndexPath = indexPath;
    currentWallet = [walletsList objectAtIndex:indexPath.row];
    if (indexPath == nil)
        NSLog(@"long press on table view but not on a row");
    else
        NSLog(@"long press on table view at row %d", indexPath.row);
    
    CGRect currentRowFrame = CGRectMake(0, 0, 320, kRowHeight);
    currentRowFrame.origin.y = kRowHeight * (indexPath.row +1) +30;
    
    
    
    if (popup == nil) {
        popup = [[SNPopupView alloc] initWithContentView:popupView contentSize:CGSizeMake(203, 50)];
		
        [popup presentModalAtPoint:CGPointMake(currentRowFrame.origin.x, currentRowFrame.origin.y) inView:self.view animated:YES];
		
		[popup addTarget:self action:@selector(didTouchPopupView:)];
		//[popup release];
		[popup setDelegate:self];
	}
	else if (NO) {
		[popup dismiss:YES];
		popup = nil;
	}


}

#pragma mark - PopUp Delegate

- (void)didTouchPopupView:(SNPopupView*)sender {
//	DNSLogMethod
//	DNSLog(@"%@", sender);
}



- (void)didDismissModal:(SNPopupView*)popupview {
	//DNSLogMethod
	if (popupview == popup) {
		popup = nil;
	}
}

#pragma mark - Reload Table View
- (void) reloadTableView :(NSNotification *)notification {
    [walletsList removeAllObjects];
    walletsList = [NSMutableArray arrayWithArray: [DataBaseAccess getAllWallet]];
    [table reloadData];
}
@end
